layui.define(['jquery'], function (exports) {
    var $ = layui.jquery;
    var util = {
        form: {
            /**
             * 将表单内容序列化为json对象
             * @param frm   表单Id
             * @returns {{}}
             */
            serializeJSON: function (frm) {
                var o = {};
                var a = $(frm).serializeArray();
                // console.log($(frm))
                $.each(a, function () {
                    if (o[this.name]) {
                        if (!o[this.name].push) {
                            o[this.name] = [o[this.name]];
                        }
                        o[this.name].push(this.value || '');
                    } else {
                        o[this.name] = this.value || '';
                    }
                });
                return o;
            },
            /**
             * 将表单内容序列化进表单里面
             * @param data  表单数据
             * @param frm   表单formId
             */
            serializeByClass: function (frm,data) {
                for (var key in data) {
                    var obj = $("#"+frm + " ." + key);
                    if (obj.length == 0) {
                        obj = $("#" + frm + " .s-" + key);
                        if (obj.length == 0) {
                            continue;
                        }
                    }
                    var tagName = obj[0].tagName;
                    if (tagName == 'INPUT') {
                        var type = obj[0].type;
                        if (type == 'text' || type == 'hidden') {
                            obj.val(data[key]);
                        } else if (type == 'checkbox') {
                            obj.attr("checked", data[key] ? true : false);
                        } else if (type = 'radio') {
                            for (var i = 0; i < obj.length; i++) {
                                if (obj.eq(i).val() == data[key]) {
                                    obj.eq(i).attr("checked", true);
                                    return;
                                }
                            }
                        }
                    } else if (tagName == 'SELECT') {
                        obj.find("option").removeAttr("selected");
                        obj.find("option[value='" + data[key] + "']").prop("selected", "true");
                    } else if (tagName = 'TEXTAREA') {
                        obj.val(data[key]);
                    }
                }
            }
        }
    }
    exports('global', util)
})